import React from 'react';
import { Modal, Button, Upload, Select, Icon, List, Tooltip, message, Popconfirm, Checkbox, Menu, Row, Col } from 'antd';
import { connect } from 'dva';
import PropTypes from "prop-types";
// import { getToken } from "../../common/PateoForm/utils/helper";
import { downloadFileByUrl } from "@/utils/utils";

@connect(state => ({
  materialAudio: state.materialAudio,
}))
export default class UploadModal extends React.PureComponent {
  static contextTypes = {
    dicData: PropTypes.object,
  };

  state = {
    buttonLoading: false,
    fileList: [],
    templateFileUrl: '',
    importDatas:[],
    fileName:'',
    btnLoading:false,
  };

  componentDidMount() {
    const { dispatch } = this.props
    dispatch({
      type: 'basedata/fetchTemplate',
      payload: { templateCode: 'dealerLibrary' },
      callback: res => this.setState({ templateFileUrl: res.data ? res.data.templateUrl : '' })
    });
  };

  handleChange = (info) => {
    const { handleClose,dispatch } = this.props;
    let { fileList, file } = info;

    if (file.type != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" && file.type != "application/vnd.ms-excel") {
      message.error('请上传xlsx格式的文件!');
      return false;
    }
    if (file.size / 1024 / 1024 > 2) {
      message.error('文件大小不能大于2MB!');
      return false;
    }
    this.setState({
      buttonLoading: true,
    })
    fileList = fileList.slice(-1);
    fileList = fileList.filter((file) => {

      if (file.response) {
        if (file.response.statusCode !== "0") {
          message.error(file.response.statusMessage);
          this.setState({
            buttonLoading: false,
            fileName: '',
            importDatas:[]
          })
          return false;
        } else {
          this.setState({dealerFences:file.response.data});
          this.setState({
            buttonLoading: false,
            fileName: file.name,
            importDatas:file.response.data
          })
          return true;
        }
      }
      this.setState({
        buttonLoading: false,
        fileName: '',
        importDatas:[]
      })
      return true;
    });
    this.setState({ fileList });
  }

  handleClose=()=>{
    this.setState({
      buttonLoading: false,
      fileName: '',
      dealerFences:[]
    })

    this.props.handleClose();
  }

  handleSubmit(){
    const { fileName,importDatas} = this.state;
    const { dispatch , handleFlushPage} = this.props;

    if(fileName == ''){
      message.error("请上传文件");
      return;
    }

    if(!importDatas || importDatas.length < 1){
      message.error("文件数据不能为空");
      return;
    }

    this.setState({btnLoading: true})

    let url = '/dealer/library/import';
    
    dispatch({
      type: 'common/arrayPost',
      payload: { url, list: importDatas },
      callback: (res)=>{
        if(res.statusCode == "0"){
          message.success('导入成功');
          this.handleClose();
        }else{
          message.error(res.statusMessage);
        }

        this.setState({btnLoading: false})
      }
    })
  }

  render() {
    const { buttonLoading, templateFileUrl ,fileName , btnLoading } = this.state;
    const { modalVisible , title } = this.props;
    const domain = window.g.url;
    const url = '/common/import/dealer/library';
    const str = `${domain}${url}`;
    const props = {
      action: str,
      onChange: this.handleChange,
      multiple: false,
    };

    let templateName = '经销商主库信息导入模板-' + new Date().getTime() + '.xlsx';

    return (
      <Modal
        width='40%'
        title={title}
        visible={modalVisible}
        onCancel={() => this.handleClose()}
        footer={[
          <Button key="back" size="default" onClick={() => this.handleClose()}>
            取消
          </Button>,
          <Button key="submit" type="primary" size="default"  onClick={() => this.handleSubmit()} loading={btnLoading}>
            确认
          </Button>
        ]}
      >
        <Upload
          {...props}
          fileList={this.state.fileList}
          showUploadList={false}
        >
          <Button loading={buttonLoading} icon="upload" type="primary" >
            导入
          </Button>
        </Upload>&nbsp;&nbsp;&nbsp;&nbsp;
        {
          templateFileUrl === '' ?
            <a disabled title="点击下载模板文件" >暂无模板下载</a>
            :
            <a onClick={()=> {downloadFileByUrl(this.state.templateFileUrl, templateName)}} title="点击下载模板文件" >模板文件下载</a>}

        {fileName != '' ?
          (<Row>
            <Col span={24}><a>{fileName}</a></Col>
          </Row>)
          : ""
        }
      </Modal>
    )
  }
}
